from django.shortcuts import render

# Create your views here.
from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http.response import HttpResponse,HttpResponseBadRequest,JsonResponse
from libs.yuntongxun.sms import CCP
from random import randint
from utils.response_code import RETCODE
import logging
logger = logging.getLogger('django')


class Img(View):
    def get(self, request, uuid):
        text, img = captcha.generate_captcha()
        con = get_redis_connection('code')
        con.setex('img_%s' % uuid, 120, text)
        return HttpResponse(img, content_type='image/jpeg')


class Sms(View):
    def get(self, request):
        # 接收数据（手机号、验证码id、用户输入的验证码）
        data = request.GET
        mobile = data.get('mobile')
        img_code_id = data.get('image_code_id')
        img_code = data.get('image_code')
        print(mobile, img_code_id, img_code)

        # 校验数据(校验验证码是否过期，校验用户验证码与数据库验证码是否相同，校验用户是否频繁发送短信)
        try:
            con = get_redis_connection('code')
            text = con.get('img_%s' % img_code_id)
            send_flag = con.get('send_flag')
            if text is None:
                return HttpResponseBadRequest('验证码已过期')
            if img_code.lower() != text.decode().lower():
                return HttpResponseBadRequest('验证码错误')
            if send_flag is not None:
                return HttpResponseBadRequest('操作太频繁了')
            con.delete('img_%s'%img_code_id)
        except Exception as e:
            logger.error(e)
            return HttpResponseBadRequest('数据库连接错误')

        # 处理数据（利用管道保存数据，异步发送短信）
        msg = '%06d'%randint(0, 999999)
        print(msg)
        pl = con.pipeline()
        pl = pl.setex('msg_%s'%mobile, 120, msg)
        pl = pl.setex('send_flag', 60, 1)
        pl.execute()

        CCP().send_template_sms(mobile, [msg, 5], 1)

        # 返回响应
        return JsonResponse({'code': RETCODE.OK})
